'''
Created on 12/03/2010

@author: igonzalez
'''

from django.http import HttpResponse
from format.utils import  getResponseFormat, generateResponse

from os import path
from xml.dom import minidom
import copy

from GIC.Channels.Items.NoteItem import *
from GIC.Channels.GenericChannel import *

PAGE = 0
N_ELEMS = 20

class CplaceLoader(object):
    

    def __init__(self):
        self.array = []
        self.count = 0
        
        #this function generates a geonode array using the xml that openadaptor has generated
    def generate_Array(self, channel,category):
        channel = channel.lower()
        category = category.lower()
        direccion = self.getPath()
        xml = str(direccion) + "/agregator_files/xmlConf/" + channel + "_" + category + ".xml"
        xmldoc = minidom.parse(xml)
        son = xmldoc.firstChild
        self.count = int(son.getAttribute('size'))
        placeList = son.getElementsByTagName(category)
        #there are thre kind of places, 11870 places, geonames places, and genereic places
        if (channel == '11870'):
            self.generate_11870Place(channel, category, placeList)
        else: 
            if (channel == 'geonames'):
                self.generate_GeonamesPlace(channel, category, placeList)  
            else:
                self.generate_Generic(channel, category, placeList) 
        return self.array
        
        #this function manages the geonode generation with httpresponse only useful for petitions without client 
    def generate_all(self, channel, category, request):  
        format = getResponseFormat (request)      
        channel = str(channel.lower())
        category = str(category.lower())               
        #calls the generate array function             
        self.generate_Array(channel,category)
        #makes the pagination and returns a HttpResponse with the geonodes using a template
        f, t, page, elems = self.get_limits(request)
        array2 = copy.deepcopy(self.array)
        self.array = self.select_limits (f, t, array2)
        data = {'code'    : '200',
                'id_type' : str(category) + 's',
                'places'  : self.array,
                'page'    : page,
                'elems'   : len(self.array),
                'type'    : str(category) + "_list" }
        return generateResponse(format, data, "place/list")  
          
          #this function will generate a geonodes array for Geonames  
    def generate_GeonamesPlace(self, channel, category, placeList):
        i = 0
        while(i < self.count):
            tempPlace = NoteItem()
            tempPlace.id = placeList[i].getAttribute('id')
            tempLatitude = ""
            tempLongitude = ""
            name = placeList[i].getElementsByTagName('name')
            if (len(name) > 0):
                if (name[0].firstChild != None):
                    tempPlace.title = name[0].firstChild.nodeValue
            longitude = placeList[i].getElementsByTagName('longitude')
            if (len(longitude) > 0):
                if (longitude[0].firstChild != None):
                    tempLongitude = longitude[0].firstChild.nodeValue
            latitude = placeList[i].getElementsByTagName('latitude')
            if (len(latitude) > 0):
                if (latitude[0].firstChild != None):
                    tempLatitude = latitude[0].firstChild.nodeValue
            tempPlace.position = { 'latitude' : str(copy.deepcopy(tempLatitude)),
                                   'longitude' : str(copy.deepcopy(tempLongitude))}
            tempPlace.icon = "/social/layer/" + channel + "/icon"
            self.array.append(copy.deepcopy(tempPlace))
            i = i + 1                          
          
          #this function will generate a geonodes array for another places except 11870 and geonames 
    def generate_Generic(self, channel, category, placeList):
        i = 0
        while(i < self.count):
            tempPlace = NoteItem()
            tempPlace.id = placeList[i].getAttribute('id')
            tempLatitude = ""
            tempLongitude = ""
            name = placeList[i].getElementsByTagName('name')
            if (len(name) > 0):
                if (name[0].firstChild != None):
                    tempPlace.title = name[0].firstChild.nodeValue
            longitude = placeList[i].getElementsByTagName('longitude')
            if (len(longitude) > 0):
                if (longitude[0].firstChild != None):
                    tempLongitude = longitude[0].firstChild.nodeValue
            latitude = placeList[i].getElementsByTagName('latitude')
            if (len(latitude) > 0):
                if (latitude[0].firstChild != None):
                    tempLatitude = latitude[0].firstChild.nodeValue
            tempPlace.position = { 'latitude' : str(copy.deepcopy(tempLatitude)),
                                   'longitude' : str(copy.deepcopy(tempLongitude))} 
            tempPlace.icon = "/social/layer/" + channel + "/icon"   
            self.array.append(copy.deepcopy(tempPlace))
            i = i + 1 
            
           #this function will generate a geonodes array for 11870        
    def generate_11870Place(self, channel, category, placeList):
        i = 0
        while(i < self.count):
            tempPlace = NoteItem()
            tempPlace.id = placeList[i].getAttribute('id')
            name = placeList[i].getElementsByTagName('name')
            if (len(name) > 0):
                if (name[0].firstChild != None):
                    tempPlace.title = name[0].firstChild.nodeValue
            summary = placeList[i].getElementsByTagName('summary')
            if (len(summary) > 0):
                if (summary[0].firstChild != None):
                    tempPlace.text = summary[0].firstChild.nodeValue
            posList = placeList[i].getElementsByTagName('position')
            if (len(posList) > 0):
                if (posList[0].firstChild != None):  
                    position = posList[0].firstChild.nodeValue
                    pos = position.split(' ')
                    tempPlace.position = { 'latitude' : str(copy.deepcopy(pos[0])),
                                           'longitude' : str(copy.deepcopy(pos[1]))}
            tempPlace.icon = "/social/layer/" + channel + "/icon"
            self.array.append(copy.deepcopy(tempPlace))
            i = i + 1  
             
    def select_limits(self, from_limit, to_limit, nodes):
        return nodes[from_limit:to_limit]        
            
    def get_limits(self, request):
        if "page" in request.REQUEST:
            page = request.REQUEST["page"]
        else:
            page = None
        if "elems" in request.REQUEST:
            elems = request.REQUEST["elems"]
        else:
            elems = None
        try:
            page = int(page) - 1
            if page < 0:
                raise ValueError()
        except:
            page = PAGE
        try:
            elems = int(elems)
            if elems < 0:
                raise ValueError()
        except:
            elems=N_ELEMS
        f = elems * page
        t = f + elems
        return (f, t, page+1, elems)         
               
    def getPath(self):
        direccion2 = path.dirname(path.abspath(__file__))
        return direccion2
        